/***************************************************************************
 *   Copyright (C) 2009 by Zheng Yonglei
 *   zhengyonglei@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "SelectListDialog.h"

ListStatusAreaWidgets::ListStatusAreaWidgets(QString name, int finishedCount, int totalCount, QWidget *parent):
	QWidget(parent),
	mListName(name),
	mFinishedCount(finishedCount),
	mTotalCount(totalCount)
{
	setLabel();
	setProgressBar();
	setCheckButton();
	setConnections();
}

ListStatusAreaWidgets::~ListStatusAreaWidgets()
{
	delete listLabel;
	delete listProgressBar;
	delete listCheckedButton;
}

void ListStatusAreaWidgets::setConnections()
{
	QObject::connect(this->listCheckedButton, SIGNAL(clicked()),this, SLOT(listSelected()));
}

void ListStatusAreaWidgets::setLabel()
{
	QString name = mListName;
	name.append(QString("(%1/").arg(mFinishedCount));
	name.append(QString("%1)").arg(mTotalCount));
	listLabel = new QLabel(name);
}

void ListStatusAreaWidgets::setProgressBar()
{
	listProgressBar = new QProgressBar();
	QSizePolicy sizePolity = QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
	listProgressBar->setSizePolicy(sizePolity);
	listProgressBar->setMinimumHeight(25);
	listProgressBar->setAlignment(Qt::AlignHCenter);
	listProgressBar->setTextVisible(true);
	listProgressBar->setMaximum(mTotalCount);
	listProgressBar->setValue(mFinishedCount);
}

void ListStatusAreaWidgets::setCheckButton()
{
	listCheckedButton = new QRadioButton();
}

SelectListDialog::SelectListDialog(QDialog *parent)
    : QDialog(parent),
   // mNeedSetListStatusTab(true),
    mListTab(NULL),
    mTabGrid(NULL),
    //mNewOrientalListsGrid(NULL),
    //mCustomListsGrid(NULL),
    mNewOrientalListsScrollArea(NULL),
    mCustomListsScrollArea(NULL)
    //mNewOrientalListsTabWidget(NULL),
    //mCustomListsTabWidget(NULL)
{
	ui.setupUi(this);
	//setListStatusArea();
	//QShortcut* closeShortcut = new QShortcut(QKeySequence(Qt::Key_Escape),  this);
	//QObject::connect(closeShortcut,SIGNAL(activated()),this,SLOT(accept()));

	QObject::connect(ui.browseSelectedListButton, SIGNAL(clicked()), this, SLOT(browseSelectedList()));
	QObject::connect(ui.reciteSelectedListButton, SIGNAL(clicked()), this, SLOT(reciteSelectedList()));
	QObject::connect(ui.closeSelectListDialogButton, SIGNAL(clicked()), this, SLOT(accept()));

	//this->setWindowFlags(Qt::WindowStaysOnTopHint);
}

SelectListDialog::~SelectListDialog()
{
}

void SelectListDialog::showThisDialog()
{
	cout<<"SelectListDialog::showThisDialog"<<endl;
	mSelectedList.clear();
	ui.totalFinishedCountProgressBar->setValue(0);
	setListStatusArea();

	QString queryCommand;
	queryCommand = "select count(id) from history;";
	DB.execQuery(queryCommand, QueryT_Read, DB.mUsrMain);
	int totalWordsCount = DB.getTableValue(0, "count(id)").toInt();

	//queryCommand.clear();
	queryCommand = QString("select count(id) from history where last_reciting_status=%1 ").arg(WS_Finished);
	queryCommand.append(QString(" or last_reciting_status=%1;").arg(WS_Reviewing));
	DB.execQuery(queryCommand, QueryT_Read, DB.mUsrMain);
	int finishedCount = DB.getTableValue(0, "count(id)").toInt();

	ui.totalFinishedCountProgressBar->setMinimum(1);
	ui.totalFinishedCountProgressBar->setMaximum(totalWordsCount);
	ui.totalFinishedCountProgressBar->setValue(finishedCount);

	QString statisticString = QString("Words Statistics: Total words:%1").arg(totalWordsCount);
	statisticString.append(QString("\tFinished Words:%1").arg(finishedCount));
	ui.wordStatisticsLabel->setText(statisticString);

	this->exec();
}

void SelectListDialog::setListStatusArea()
{
	cout<<"SelectListDialog::setListStatusArea"<<endl;
	for (int i=0; i<mNewOrientalListStatusAreaWidgets.size(); i++)
		delete mNewOrientalListStatusAreaWidgets[i];
	mNewOrientalListStatusAreaWidgets.clear();

	for (int i=0; i<mCustomListStatusAreaWidgets.size(); i++)
		delete mCustomListStatusAreaWidgets[i];
	mCustomListStatusAreaWidgets.clear();

	if (mListTab)
		delete mListTab;
	if (mTabGrid)
		delete mTabGrid;

	QString queryCommand;
	vector<int> totalCount;
	vector<int> finishedCount;

	mListTab = new QTabWidget(this);
	mTabGrid = new QGridLayout(ui.listInfoWidget);
	mTabGrid->addWidget(mListTab, 0, 0);

	//new oriental lists
	QWidget* newOrientalListsTabWidget = new QWidget(this);
	QGridLayout* newOrientalListsGrid = new QGridLayout(newOrientalListsTabWidget);

	totalCount.clear();
	queryCommand = QString(
			"select red_bible_list,count(id) "
			"from lists "
			"where red_bible_list>0 "
			"group by red_bible_list;");
	DB.execQuery(queryCommand, QueryT_Read, DB.mUsrMain);
	for (int i=0; i<DB.getRowCount(); i++)
	{
		int listID = DB.getTableValue(i, "red_bible_list").toInt();
		while(listID != totalCount.size()+1)
			totalCount.push_back(0);
		int wordCount = DB.getTableValue(i, "count(id)").toInt();
		totalCount.push_back(wordCount);
		//cout<<"i="<<i<<"\tlistID="<<listID<<endl;
		/*if (listID == i+1)
		{
			int wordCount = DB.getTableValue(i, "count(id)").toInt();
			totalCount.push_back(wordCount);
		}
		else
		{
			cout<<"SelectListDialog::setListStatusArea-->listID="<<listID<<"\ti="<<i<<endl;
			assert(0);
		}*/
	}

	finishedCount.clear();
	queryCommand = QString(
			"select lists.red_bible_list,count(lists.id) "
			"from lists,history "
			"where ("
			"red_bible_list>0 and ");
	queryCommand.append(QString("lists.id = history.id and (history.last_reciting_status=%1 ").arg(WS_Finished));
	queryCommand.append(QString("or history.last_reciting_status =%1)) ").arg(WS_Reviewing));
	queryCommand.append(QString("group by lists.red_bible_list"));
	DB.execQuery(queryCommand, QueryT_Read, DB.mUsrMain);
	for (int i=0; i<DB.getRowCount(); i++)
	{
		int listID = DB.getTableValue(i, 0).toInt();
		//cout<<"i="<<i<<"\tlistID="<<listID<<endl;
		while(listID != finishedCount.size()+1)
			finishedCount.push_back(0);
		int wordCount = DB.getTableValue(i, "count(lists.id)").toInt();
		finishedCount.push_back(wordCount);
		/*if (listID == i+1)
		{
			int wordCount = DB.getTableValue(i, "count(lists.id)").toInt();
			finishedCount.push_back(wordCount);
		}
		else
		{
			cout<<"SelectListDialog::setListStatusArea-->listID="<<listID<<"\ti="<<i<<endl;
			assert(0);
		}*/
	}

	//assert(totalCount.size() == finishedCount.size());
	for (int i=0; i<totalCount.size(); i++)
	{
		int finishedWordCount;
		int wordCount;
		wordCount = totalCount[i];
		if (i < finishedCount.size())
			finishedWordCount = finishedCount[i];
		else
			finishedWordCount = 0;
		QString listName = QString("list%1").arg(i+1, 2, 10, QChar('0'));
		mNewOrientalListStatusAreaWidgets.push_back(new ListStatusAreaWidgets(listName, finishedWordCount, wordCount));
		newOrientalListsGrid->addWidget(mNewOrientalListStatusAreaWidgets[i]->listLabel, i, 0);
		newOrientalListsGrid->addWidget(mNewOrientalListStatusAreaWidgets[i]->listCheckedButton, i, 1);
		newOrientalListsGrid->addWidget(mNewOrientalListStatusAreaWidgets[i]->listProgressBar, i, 2);
		QObject::connect(mNewOrientalListStatusAreaWidgets[i], SIGNAL(selectedListName(QString)),
							this, SLOT(listSelected(QString)));
	}

	//set custom list tab
	QWidget* customListsTabWidget = new QWidget(this);
	QGridLayout* customListsGrid = new QGridLayout(customListsTabWidget);

	totalCount.clear();
	queryCommand = QString(
			"select custom_list,count(id) "
			"from lists "
			"where custom_list>0 "
			"group by custom_list;");
	DB.execQuery(queryCommand, QueryT_Read, DB.mUsrMain);
	//default is 0
	for (int i=0; i<DB.getRowCount(); i++)
	{
		int listID = DB.getTableValue(i, "custom_list").toInt();
		while(listID != totalCount.size()+1)
			totalCount.push_back(0);
		int wordCount = DB.getTableValue(i, 1).toInt();
		totalCount.push_back(wordCount);
		//cout<<"i="<<i<<"\tlistID="<<listID<<endl;
		/*if (listID == i+1)
		{
			int wordCount = DB.getTableValue(i, 1).toInt();
			totalCount.push_back(wordCount);
		}
		else
		{
			cout<<"SelectListDialog::setListStatusArea-->listID="<<listID<<"\ti="<<i<<endl;
			assert(0);
		}*/
	}

	finishedCount.clear();
	queryCommand = QString(
			"select lists.custom_list, count(lists.id) "
			"from lists,history "
			"where ("
			"lists.custom_list>0 and ");
	queryCommand.append(QString("lists.id = history.id and (history.last_reciting_status = %1 ").arg(WS_Finished));
	queryCommand.append(QString("or history.last_reciting_status = %1))").arg(WS_Reviewing));
	queryCommand.append(QString("group by lists.custom_list"));
	DB.execQuery(queryCommand, QueryT_Read, DB.mUsrMain);
	for (int i=0; i<DB.getRowCount(); i++)
	{
		int listID = DB.getTableValue(i, 0).toInt();
		while(listID != finishedCount.size()+1)
			finishedCount.push_back(0);
		int wordCount = DB.getTableValue(i, "count(lists.id)").toInt();
		finishedCount.push_back(wordCount);
		//cout<<"i="<<i<<"\tlistID="<<listID<<endl;
		/*if (listID == i+1)
		{
			int wordCount = DB.getTableValue(i, "count(lists.id)").toInt();
			finishedCount.push_back(wordCount);
		}
		else
		{
			cout<<"SelectListDialog::setListStatusArea-->listID="<<listID<<"\ti="<<i<<endl;
			assert(0);
		}*/
	}

	//assert(totalCount.size() == finishedCount.size());
	for (int i=0; i<totalCount.size(); i++)
	{
		int finishedWordCount;
		int wordCount;
		wordCount = totalCount[i];
		if (i < finishedCount.size())
			finishedWordCount = finishedCount[i];
		else
			finishedWordCount = 0;
		QString listName = QString("list%1").arg(i+1, 2, 10, QChar('0'));
		mCustomListStatusAreaWidgets.push_back(new ListStatusAreaWidgets(listName, finishedWordCount, wordCount));
		customListsGrid->addWidget(mCustomListStatusAreaWidgets[i]->listLabel, i, 0);
		customListsGrid->addWidget(mCustomListStatusAreaWidgets[i]->listCheckedButton, i, 1);
		customListsGrid->addWidget(mCustomListStatusAreaWidgets[i]->listProgressBar, i, 2);
		QObject::connect(mCustomListStatusAreaWidgets[i], SIGNAL(selectedListName(QString)),
							this, SLOT(listSelected(QString)));
	}

	mNewOrientalListsScrollArea = new QScrollArea(this);
	mNewOrientalListsScrollArea->setWidgetResizable(true);
	mNewOrientalListsScrollArea->setWidget(newOrientalListsTabWidget);

	mCustomListsScrollArea = new QScrollArea(this);
	mCustomListsScrollArea->setWidgetResizable(true);
	mCustomListsScrollArea->setWidget(customListsTabWidget);
	//add tabs
	mListTab->insertTab(0, mNewOrientalListsScrollArea, "New Oriental Lists");
	mListTab->insertTab(1, mCustomListsScrollArea, "Custom Lists");
}

void SelectListDialog::listSelected(QString selectedList)
{
	mSelectedList = selectedList;
	cout<<"SelectListDialog::listSelected-->mSelectedList = "<<mSelectedList.toUtf8().data()<<endl;
}

void SelectListDialog::reciteSelectedList()
{
	WM.finishLastTask();
	if(!mSelectedList.isEmpty())
	{
		WordManagerTask task;
		task.taskType = TaskType_Recite;
		task.selectWordMethod = select_by_list_name;
		task.listName = mSelectedList;
		if (mListTab->currentIndex() == 0)
			task.listType = red_bible_list;
		else
			task.listType = custom_list;

		this->accept();
		WM.setTask(task);
		emit(reciteTask());
	}
}

void SelectListDialog::browseSelectedList()
{
	WM.finishLastTask();
	if(!mSelectedList.isEmpty())
	{
		WordManagerTask task;
		task.taskType = TaskType_Browse;
		task.selectWordMethod = select_by_list_name;
		task.listName = mSelectedList;
		if (mListTab->currentIndex() == 0)
			task.listType = red_bible_list;
		else
			task.listType = custom_list;

		this->accept();
		WM.setTask(task);
		emit(browseTask());
	}
}
